package com.gs.zsmanage.web.controller;

import com.gs.zsmanage.entity.CustomLive;
import com.gs.zsmanage.entity.CustomWarning;
import com.gs.zsmanage.entity.Department;
import com.gs.zsmanage.entity.MonitorSite;
import com.gs.zsmanage.entity.MonitorSiteConfig;
import com.gs.zsmanage.entity.User;
import com.gs.zsmanage.service.CustomLiveService;
import com.gs.zsmanage.service.CustomMenuService;
import com.gs.zsmanage.service.CustomWarningService;
import com.gs.zsmanage.service.MonitorSiteService;
import com.gs.zsmanage.service.UserService;
import com.gs.zsmanage.utils.HttpUtils;
import com.gs.zsmanage.utils.ShiroSession;
import com.gs.zsmanage.vo.IdAndName;
import com.gs.zsmanage.vo.MenuVO;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Controller
public class PageController {

    @Autowired
    UserService userService;
    @Autowired
    CustomWarningService customWarningService;
    @Autowired
    CustomLiveService customLiveService;
    @Autowired
    CustomMenuService customMenuService;
    @Autowired
    MonitorSiteService monitorSiteService;

    @RequestMapping("test")
    @ResponseBody
    public String indexPage() {
        return "test!";
    }

    @RequestMapping("/")
    public String index(Model model) {
        List<Department> departments = userService.getAllDepartments();
        List<User> users = userService.getAllUsers();
        model.addAttribute("departments", departments);
        model.addAttribute("users", users);
        return "user";
    }

    @RequestMapping("user")
    public String userPage(Model model) {
        List<Department> departments = userService.getAllDepartments();
        List<User> users = userService.getAllUsers();
        model.addAttribute("departments", departments);
        model.addAttribute("users", users);
        return "user";
    }

    @RequestMapping("user/{department}")
    public String userPage(@PathVariable("department") String department, Model model) {
        List<User> users;
        if ("全部".equals(department)) {
            users = userService.getAllUsers();
        } else {
            users = userService.getUsersByDepartment(department);
        }
        List<Department> departments = userService.getAllDepartments();
        model.addAttribute("cdepart", department);
        model.addAttribute("departments", departments);
        model.addAttribute("users", users);
        return "user";
    }

    @RequestMapping("user/search/{name}")
    public String searchUser(@PathVariable("name") String name, Model model) {
        List<Department> departments = userService.getAllDepartments();
        List<User> users = userService.searchUsers(name);
        model.addAttribute("departments", departments);
        model.addAttribute("users", users);
        return "user";
    }


    @RequestMapping("department")
    public String departmentPage(Model model) {
        List<Department> departments = userService.getAllDepartments();
        model.addAttribute("departments", departments);
        return "department";
    }

    @RequestMapping("menu")
    public String menuPage(Model model) {
        List<Department> departments = userService.getAllDepartments();
        Map map = customMenuService.getMenusAndIdsByDepartment(departments.get(0).getName());
        List<MenuVO> allMenus = customMenuService.getAllMenus();
        List<Integer> customIds = (List<Integer>) map.get("customIds");
        model.addAttribute("departments", departments);
        model.addAttribute("allMenus", allMenus);
        model.addAttribute("customIds", customIds);
        return "menu";
    }

    @RequestMapping("live")
    public String livePage(Model model) {
        List<Department> departments = userService.getAllDepartments();
        List<CustomLive> customDepartments = customLiveService.getAllDepartmentsAndStationType();
        String department = customDepartments.get(0).getDepartment();
        String stationType = customDepartments.get(0).getStationType();
        CustomLive customLive = customLiveService.getCustomLiveByDepartmentAndStationType(department, stationType);
        model.addAttribute("departments", departments);
        model.addAttribute("customDepartments", customDepartments);
        model.addAttribute("customLive", customLive);
        model.addAttribute("cDepartment", department);
        model.addAttribute("cStationType", stationType);
        return "live";
    }

    @RequestMapping("live/get/{department}/{stationType}/{cPage}")
    public String updateLiveStations(@PathVariable("department") String department, @PathVariable("stationType") String stationType, @PathVariable("cPage") String cPage, Model model) {
        List<Department> departments = userService.getAllDepartments();
        List<CustomLive> customDepartments = customLiveService.getAllDepartmentsAndStationType();
        CustomLive customLive = customLiveService.getCustomLiveByDepartmentAndStationType(department, stationType);
        model.addAttribute("departments", departments);
        model.addAttribute("customDepartments", customDepartments);
        model.addAttribute("customLive", customLive);
        model.addAttribute("cDepartment", department);
        model.addAttribute("cStationType", stationType);
        model.addAttribute("cPage", cPage);
        return "live";
    }

    @RequestMapping("warning")
    public String warningPage(Model model) {
        List<Department> departments = userService.getAllDepartments();
        List<String> customNames = new ArrayList<>();
        List<CustomWarning> warnings = customWarningService.getCustomWarningByDepartment(departments.get(0).getName());
        if (warnings != null)
            for (CustomWarning warning : warnings) {
                customNames.add(warning.getName());
            }
        List<IdAndName> allWarnings = customWarningService.getAllWarning();
        model.addAttribute("departments", departments);
        model.addAttribute("allWarnings", allWarnings);
        model.addAttribute("customNames", customNames);
        return "warning";
    }

    @RequestMapping("login")
    public String loginPage() {
        return "login";
    }

    @RequestMapping("auth")
    @ResponseBody
    public String authentication(String name, String pwd, Boolean remember) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(name, pwd);
        remember = remember == null ? false : remember;
        token.setRememberMe(remember);
        try {
            subject.login(token);
            ShiroSession.setTimeout(3);
            return "/zs/user";
        } catch (
                AuthenticationException e) {
            e.printStackTrace();
            return "failed";
        } catch (
                Exception e) {
            e.printStackTrace();
            return "failed";
        }
    }

    @RequestMapping("logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/zs/login";
    }


    @RequestMapping("downFile")
    public ResponseEntity download(String aimFile) throws IOException {
        File file = new File(aimFile);
        if (file.exists()) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.TEXT_PLAIN);
            headers.setContentDispositionFormData("attachment", new String(file.getName().getBytes("gb2312"), "ISO8859-1"));
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
        }
        return HttpUtils.buildStringResponse("加载失败", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @RequestMapping("monitorSite")
    public String monitorSitePage(Model model) {
        //获取表中所有监测点
        List<MonitorSite> monitorSites = monitorSiteService.getAllMonitorSites();
        model.addAttribute("monitorSites", monitorSites);
        //获取配置所有监测点
        List<MonitorSiteConfig> monitorSiteConfig = getMonitorSiteConfig();
        model.addAttribute("monitorSiteConfig", monitorSiteConfig);
        return "monitorSite";
    }

    private List<MonitorSiteConfig> getMonitorSiteConfig() {
        List<MonitorSiteConfig> result = new ArrayList<MonitorSiteConfig>();
        URL classPath = Thread.currentThread().getContextClassLoader().getResource("");
        try {
            String proFilePath = URLDecoder.decode(classPath.toString(), "UTF-8");
            //移除开通的file:/六个字符
            proFilePath = proFilePath.substring(6);
            //如果为window系统下,则把路径中的路径分隔符替换为window系统的文件路径分隔符
            proFilePath = proFilePath.replace("/", java.io.File.separator);
            proFilePath += "\\data\\monitorSite.txt";
            File file = new File(proFilePath);
            FileInputStream in = new FileInputStream(file);
            // size 为字串的长度 ，这里一次性读完
            int size = in.available();
            byte[] buffer = new byte[size];
            in.read(buffer);
            in.close();
            String str = new String(buffer, "utf-8");
            for (String site : Arrays.asList(str.split("\r\n"))) {
                MonitorSiteConfig m = new MonitorSiteConfig();
                m.setIndexCode(site.split(" ")[0]);
                m.setName(site.split(" ")[1]);
                result.add(m);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
}
